<!DOCTYPE html>
<html lang="en-US">
<head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="language" content="en" />
        <link href="./assets/ffd55088/css/bootstrap.css" rel="stylesheet">
<link href="./assets/5cf9384a/solarized_light.css" rel="stylesheet">
<link href="./assets/6c54116e/style.css" rel="stylesheet">
<script src="./assets/a44cef0f/jquery.js"></script>
<script src="./assets/ffd55088/js/bootstrap.js"></script>
<script src="./assets/8ac4e28a/jssearch.js"></script>    <title>Migrations - Working with Databases - The Definitive Guide to Yii 2.0</title>
</head>
<body>

<div class="wrap">
    <nav id="w928" class="navbar-inverse navbar-fixed-top navbar" role="navigation"><div class="navbar-header"><button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#w928-collapse"><span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span></button><a class="navbar-brand" href="./index.html">The Definitive Guide to Yii 2.0</a></div><div id="w928-collapse" class="collapse navbar-collapse"><ul id="w929" class="navbar-nav nav"><li><a href="./index.html">Class reference</a></li>
<li class="dropdown"><a class="dropdown-toggle" href="#" data-toggle="dropdown">Extensions <b class="caret"></b></a><ul id="w930" class="dropdown-menu"><li><a href="./ext-apidoc-index.html" tabindex="-1">apidoc</a></li>
<li><a href="./ext-authclient-index.html" tabindex="-1">authclient</a></li>
<li><a href="./ext-bootstrap-index.html" tabindex="-1">bootstrap</a></li>
<li><a href="./ext-codeception-index.html" tabindex="-1">codeception</a></li>
<li><a href="./ext-debug-index.html" tabindex="-1">debug</a></li>
<li><a href="./ext-elasticsearch-index.html" tabindex="-1">elasticsearch</a></li>
<li><a href="./ext-faker-index.html" tabindex="-1">faker</a></li>
<li><a href="./ext-gii-index.html" tabindex="-1">gii</a></li>
<li><a href="./ext-imagine-index.html" tabindex="-1">imagine</a></li>
<li><a href="./ext-jui-index.html" tabindex="-1">jui</a></li>
<li><a href="./ext-mongodb-index.html" tabindex="-1">mongodb</a></li>
<li><a href="./ext-redis-index.html" tabindex="-1">redis</a></li>
<li><a href="./ext-smarty-index.html" tabindex="-1">smarty</a></li>
<li><a href="./ext-sphinx-index.html" tabindex="-1">sphinx</a></li>
<li><a href="./ext-swiftmailer-index.html" tabindex="-1">swiftmailer</a></li>
<li><a href="./ext-twig-index.html" tabindex="-1">twig</a></li></ul></li>
<li><a href="./guide-README.html">Guide</a></li></ul><div class="navbar-form navbar-left" role="search">
  <div class="form-group">
    <input id="searchbox" type="text" class="form-control" placeholder="Search">
  </div>
</div>
</div></nav>
    <div id="search-resultbox" style="display: none;" class="modal-content">
        <ul id="search-results">
        </ul>
    </div>

    
<div class="row">
    <div class="col-md-2">
                <div id="navigation" class="list-group"><a class="list-group-item" href="#navigation-912" data-toggle="collapse" data-parent="#navigation">Introduction <b class="caret"></b></a><div id="navigation-912" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-intro-yii.html">About Yii</a>
<a class="list-group-item" href="./guide-intro-upgrade-from-v1.html">Upgrading from Version 1.1</a></div>
<a class="list-group-item" href="#navigation-913" data-toggle="collapse" data-parent="#navigation">Getting Started <b class="caret"></b></a><div id="navigation-913" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-start-installation.html">Installing Yii</a>
<a class="list-group-item" href="./guide-start-workflow.html">Running Applications</a>
<a class="list-group-item" href="./guide-start-hello.html">Saying Hello</a>
<a class="list-group-item" href="./guide-start-forms.html">Working with Forms</a>
<a class="list-group-item" href="./guide-start-databases.html">Working with Databases</a>
<a class="list-group-item" href="./guide-start-gii.html">Generating Code with Gii</a>
<a class="list-group-item" href="./guide-start-looking-ahead.html">Looking Ahead</a></div>
<a class="list-group-item" href="#navigation-914" data-toggle="collapse" data-parent="#navigation">Application Structure <b class="caret"></b></a><div id="navigation-914" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-structure-overview.html">Overview</a>
<a class="list-group-item" href="./guide-structure-entry-scripts.html">Entry Scripts</a>
<a class="list-group-item" href="./guide-structure-applications.html">Applications</a>
<a class="list-group-item" href="./guide-structure-application-components.html">Application Components</a>
<a class="list-group-item" href="./guide-structure-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-structure-models.html">Models</a>
<a class="list-group-item" href="./guide-structure-views.html">Views</a>
<a class="list-group-item" href="./guide-structure-modules.html">Modules</a>
<a class="list-group-item" href="./guide-structure-filters.html">Filters</a>
<a class="list-group-item" href="./guide-structure-widgets.html">Widgets</a>
<a class="list-group-item" href="./guide-structure-assets.html">Assets</a>
<a class="list-group-item" href="./guide-structure-extensions.html">Extensions</a></div>
<a class="list-group-item" href="#navigation-915" data-toggle="collapse" data-parent="#navigation">Handling Requests <b class="caret"></b></a><div id="navigation-915" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-runtime-overview.html">Overview</a>
<a class="list-group-item" href="./guide-runtime-bootstrapping.html">Bootstrapping</a>
<a class="list-group-item" href="./guide-runtime-routing.html">Routing and URL Creation</a>
<a class="list-group-item" href="./guide-runtime-requests.html">Requests</a>
<a class="list-group-item" href="./guide-runtime-responses.html">Responses</a>
<a class="list-group-item" href="./guide-runtime-sessions-cookies.html">Sessions and Cookies</a>
<a class="list-group-item" href="./guide-runtime-handling-errors.html">Handling Errors</a>
<a class="list-group-item" href="./guide-runtime-logging.html">Logging</a></div>
<a class="list-group-item" href="#navigation-916" data-toggle="collapse" data-parent="#navigation">Key Concepts <b class="caret"></b></a><div id="navigation-916" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-concept-components.html">Components</a>
<a class="list-group-item" href="./guide-concept-properties.html">Properties</a>
<a class="list-group-item" href="./guide-concept-events.html">Events</a>
<a class="list-group-item" href="./guide-concept-behaviors.html">Behaviors</a>
<a class="list-group-item" href="./guide-concept-configurations.html">Configurations</a>
<a class="list-group-item" href="./guide-concept-aliases.html">Aliases</a>
<a class="list-group-item" href="./guide-concept-autoloading.html">Class Autoloading</a>
<a class="list-group-item" href="./guide-concept-service-locator.html">Service Locator</a>
<a class="list-group-item" href="./guide-concept-di-container.html">Dependency Injection Container</a></div>
<a class="list-group-item active" href="#navigation-917" data-toggle="collapse" data-parent="#navigation">Working with Databases <b class="caret"></b></a><div id="navigation-917" class="submenu panel-collapse collapse in"><a class="list-group-item" href="./guide-db-dao.html">Data Access Objects</a>
<a class="list-group-item" href="./guide-db-query-builder.html">Query Builder</a>
<a class="list-group-item" href="./guide-db-active-record.html">Active Record</a>
<a class="list-group-item active" href="./guide-db-migrations.html">Migrations</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-sphinx/blob/master/docs/guide/README.md">Sphinx</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-redis/blob/master/docs/guide/README.md">Redis</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-mongodb/blob/master/docs/guide/README.md">MongoDB</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-elasticsearch/blob/master/docs/guide/README.md">ElasticSearch</a></div>
<a class="list-group-item" href="#navigation-918" data-toggle="collapse" data-parent="#navigation">Getting Data from Users <b class="caret"></b></a><div id="navigation-918" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-input-forms.html">Creating Forms</a>
<a class="list-group-item" href="./guide-input-validation.html">Validating Input</a>
<a class="list-group-item" href="./guide-input-file-upload.html">Uploading Files</a>
<a class="list-group-item" href="./guide-input-tabular-input.html">Collecting Tabular Input</a>
<a class="list-group-item" href="./guide-input-multiple-models.html">Getting Data for Multiple Models</a></div>
<a class="list-group-item" href="#navigation-919" data-toggle="collapse" data-parent="#navigation">Displaying Data <b class="caret"></b></a><div id="navigation-919" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-output-formatting.html">Data Formatting</a>
<a class="list-group-item" href="./guide-output-pagination.html">Pagination</a>
<a class="list-group-item" href="./guide-output-sorting.html">Sorting</a>
<a class="list-group-item" href="./guide-output-data-providers.html">Data Providers</a>
<a class="list-group-item" href="./guide-output-data-widgets.html">Data Widgets</a>
<a class="list-group-item" href="./guide-output-client-scripts.html">Working with Client Scripts</a>
<a class="list-group-item" href="./guide-output-theming.html">Theming</a></div>
<a class="list-group-item" href="#navigation-920" data-toggle="collapse" data-parent="#navigation">Security <b class="caret"></b></a><div id="navigation-920" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-security-overview.html">Overview</a>
<a class="list-group-item" href="./guide-security-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-security-authorization.html">Authorization</a>
<a class="list-group-item" href="./guide-security-passwords.html">Working with Passwords</a>
<a class="list-group-item" href="./guide-security-cryptography.html">Cryptography</a>
<a class="list-group-item" href="./guide-structure-views.html#security">Views security</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-authclient/blob/master/docs/guide/README.md">Auth Clients</a>
<a class="list-group-item" href="./guide-security-best-practices.html">Best Practices</a></div>
<a class="list-group-item" href="#navigation-921" data-toggle="collapse" data-parent="#navigation">Caching <b class="caret"></b></a><div id="navigation-921" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-caching-overview.html">Overview</a>
<a class="list-group-item" href="./guide-caching-data.html">Data Caching</a>
<a class="list-group-item" href="./guide-caching-fragment.html">Fragment Caching</a>
<a class="list-group-item" href="./guide-caching-page.html">Page Caching</a>
<a class="list-group-item" href="./guide-caching-http.html">HTTP Caching</a></div>
<a class="list-group-item" href="#navigation-922" data-toggle="collapse" data-parent="#navigation">RESTful Web Services <b class="caret"></b></a><div id="navigation-922" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-rest-quick-start.html">Quick Start</a>
<a class="list-group-item" href="./guide-rest-resources.html">Resources</a>
<a class="list-group-item" href="./guide-rest-controllers.html">Controllers</a>
<a class="list-group-item" href="./guide-rest-routing.html">Routing</a>
<a class="list-group-item" href="./guide-rest-response-formatting.html">Response Formatting</a>
<a class="list-group-item" href="./guide-rest-authentication.html">Authentication</a>
<a class="list-group-item" href="./guide-rest-rate-limiting.html">Rate Limiting</a>
<a class="list-group-item" href="./guide-rest-versioning.html">Versioning</a>
<a class="list-group-item" href="./guide-rest-error-handling.html">Error Handling</a></div>
<a class="list-group-item" href="#navigation-923" data-toggle="collapse" data-parent="#navigation">Development Tools <b class="caret"></b></a><div id="navigation-923" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-debug/blob/master/docs/guide/README.md">Debug Toolbar and Debugger</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-gii/blob/master/docs/guide/README.md">Generating Code using Gii</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-apidoc">Generating API Documentation</a></div>
<a class="list-group-item" href="#navigation-924" data-toggle="collapse" data-parent="#navigation">Testing <b class="caret"></b></a><div id="navigation-924" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-test-overview.html">Overview</a>
<a class="list-group-item" href="./guide-test-environment-setup.html">Testing environment setup</a>
<a class="list-group-item" href="./guide-test-unit.html">Unit Tests</a>
<a class="list-group-item" href="./guide-test-functional.html">Functional Tests</a>
<a class="list-group-item" href="./guide-test-acceptance.html">Acceptance Tests</a>
<a class="list-group-item" href="./guide-test-fixtures.html">Fixtures</a></div>
<a class="list-group-item" href="#navigation-925" data-toggle="collapse" data-parent="#navigation">Special Topics <b class="caret"></b></a><div id="navigation-925" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-app-advanced/blob/master/docs/guide/README.md">Advanced Project Template</a>
<a class="list-group-item" href="./guide-tutorial-start-from-scratch.html">Building Application from Scratch</a>
<a class="list-group-item" href="./guide-tutorial-console.html">Console Commands</a>
<a class="list-group-item" href="./guide-tutorial-core-validators.html">Core Validators</a>
<a class="list-group-item" href="./guide-tutorial-i18n.html">Internationalization</a>
<a class="list-group-item" href="./guide-tutorial-mailing.html">Mailing</a>
<a class="list-group-item" href="./guide-tutorial-performance-tuning.html">Performance Tuning</a>
<a class="list-group-item" href="./guide-tutorial-shared-hosting.html">Shared Hosting Environment</a>
<a class="list-group-item" href="./guide-tutorial-template-engines.html">Template Engines</a>
<a class="list-group-item" href="./guide-tutorial-yii-integration.html">Working with Third-Party Code</a></div>
<a class="list-group-item" href="#navigation-926" data-toggle="collapse" data-parent="#navigation">Widgets <b class="caret"></b></a><div id="navigation-926" class="submenu panel-collapse collapse"><a class="list-group-item" href="https://github.com/yiisoft/yii2-bootstrap/blob/master/docs/guide/README.md">Bootstrap Widgets</a>
<a class="list-group-item" href="https://github.com/yiisoft/yii2-jui/blob/master/docs/guide/README.md">jQuery UI Widgets</a></div>
<a class="list-group-item" href="#navigation-927" data-toggle="collapse" data-parent="#navigation">Helpers <b class="caret"></b></a><div id="navigation-927" class="submenu panel-collapse collapse"><a class="list-group-item" href="./guide-helper-overview.html">Overview</a>
<a class="list-group-item" href="./guide-helper-array.html">ArrayHelper</a>
<a class="list-group-item" href="./guide-helper-html.html">Html</a>
<a class="list-group-item" href="./guide-helper-url.html">Url</a></div></div>    </div>
    <div class="col-md-9 guide-content" role="main">
        <h1>Database Migration <span id="database-migration"></span><a href="#database-migration" class="hashlink">&para;</a></h1>
<div class="toc"><ol><li><a href="#creating-migrations">Creating Migrations</a></li>
<li><a href="#generating-migrations">Generating Migrations</a></li>
<li><a href="#applying-migrations">Applying Migrations</a></li>
<li><a href="#reverting-migrations">Reverting Migrations</a></li>
<li><a href="#redoing-migrations">Redoing Migrations</a></li>
<li><a href="#listing-migrations">Listing Migrations</a></li>
<li><a href="#modifying-migration-history">Modifying Migration History</a></li>
<li><a href="#customizing-migrations">Customizing Migrations</a></li>
<li><a href="#migrating-multiple-databases">Migrating Multiple Databases</a></li></ol></div>
<p>During the course of developing and maintaining a database-driven application, the structure of the database
being used evolves just like the source code does. For example, during the development of an application,
a new table may be found necessary; after the application is deployed to production, it may be discovered
that an index should be created to improve the query performance; and so on. Because a database structure change
often requires some source code changes, Yii supports the so-called <em>database migration</em> feature that allows
you to keep track of database changes in terms of <em>database migrations</em> which are version-controlled together
with the source code.</p>
<p>The following steps show how database migration can be used by a team during development:</p>
<ol>
<li>Tim creates a new migration (e.g. creates a new table, changes a column definition, etc.).</li>
<li>Tim commits the new migration into the source control system (e.g. Git, Mercurial).</li>
<li>Doug updates his repository from the source control system and receives the new migration.</li>
<li>Doug applies the migration to his local development database, thereby synchronizing his database
to reflect the changes that Tim has made.</li>
</ol>
<p>And the following steps show how to deploy a new release with database migrations to production:</p>
<ol>
<li>Scott creates a release tag for the project repository that contains some new database migrations.</li>
<li>Scott updates the source code on the production server to the release tag.</li>
<li>Scott applies any accumulated database migrations to the production database.</li>
</ol>
<p>Yii provides a set of migration command line tools that allow you to:</p>
<ul>
<li>create new migrations;</li>
<li>apply migrations;</li>
<li>revert migrations;</li>
<li>re-apply migrations;</li>
<li>show migration history and status.</li>
</ul>
<p>All these tools are accessible through the command <code>yii migrate</code>. In this section we will describe in detail
how to accomplish various tasks using these tools. You may also get the usage of each tool via the help
command <code>yii help migrate</code>.</p>
<blockquote class="tip"><p><strong>Tip: </strong>migrations could affect not only database schema but adjust existing data to fit new schema, create RBAC
  hierarchy or clean up cache.</p>
</blockquote>
<h2>Creating Migrations  <span id="creating-migrations"></span><a href="#creating-migrations" class="hashlink">&para;</a></h2><p>To create a new migration, run the following command:</p>
<pre><code class="hljs sql">yii migrate/<span class="hljs-operator"><span class="hljs-keyword">create</span> &lt;<span class="hljs-keyword">name</span>&gt;
</span></code></pre>
<p>The required <code>name</code> argument gives a brief description about the new migration. For example, if
the migration is about creating a new table named <em>news</em>, you may use the name <code>create_news_table</code>
and run the following command:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate/create create_news_table
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>Because the <code>name</code> argument will be used as part of the generated migration class name,
  it should only contain letters, digits, and/or underscore characters.</p>
</blockquote>
<p>The above command will create a new PHP class file named <code>m150101_185401_create_news_table.php</code>
in the <code>@app/migrations</code> directory. The file contains the following code which mainly declares
a migration class <code>m150101_185401_create_news_table</code> with the skeleton code:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Migration</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150101_185401_create_news_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{

    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-keyword">echo</span> <span class="hljs-string">"m101129_185401_create_news_table cannot be reverted.\n"</span>;

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">false</span>;
    }

    <span class="hljs-comment">/*
    // Use safeUp/safeDown to run migration code within a transaction
    public function safeUp()
    {
    }

    public function safeDown()
    {
    }
    */</span>
}
</code></pre>
<p>Each database migration is defined as a PHP class extending from <a href="./yii-db-migration.html">yii\db\Migration</a>. The migration
class name is automatically generated in the format of <code>m&lt;YYMMDD_HHMMSS&gt;_&lt;Name&gt;</code>, where</p>
<ul>
<li><code>&lt;YYMMDD_HHMMSS&gt;</code> refers to the UTC datetime at which the migration creation command is executed.</li>
<li><code>&lt;Name&gt;</code> is the same as the value of the <code>name</code> argument that you provide to the command.</li>
</ul>
<p>In the migration class, you are expected to write code in the <code>up()</code> method that makes changes to the database structure.
You may also want to write code in the <code>down()</code> method to revert the changes made by <code>up()</code>. The <code>up()</code> method is invoked
when you upgrade the database with this migration, while the <code>down()</code> method is invoked when you downgrade the database.
The following code shows how you may implement the migration class to create a <code>news</code> table:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Schema</span>;
<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Migration</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150101_185401_create_news_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'news'</span>, [
            <span class="hljs-string">'id'</span> =&gt; Schema::TYPE_PK,
            <span class="hljs-string">'title'</span> =&gt; Schema::TYPE_STRING . <span class="hljs-string">' NOT NULL'</span>,
            <span class="hljs-string">'content'</span> =&gt; Schema::TYPE_TEXT,
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'news'</span>);
    }
}
</code></pre>
<blockquote class="info"><p><strong>Info: </strong>Not all migrations are reversible. For example, if the <code>up()</code> method deletes a row of a table, you may
  not be able to recover this row in the <code>down()</code> method. Sometimes, you may be just too lazy to implement
  the <code>down()</code>, because it is not very common to revert database migrations. In this case, you should return
  <code>false</code> in the <code>down()</code> method to indicate that the migration is not reversible.</p>
</blockquote>
<p>The base migration class <a href="./yii-db-migration.html">yii\db\Migration</a> exposes a database connection via the <a href="./yii-db-migration.html#$db-detail">db</a>
property. You can use it to manipulate the database schema using the methods as described in
<a href="guide-db-dao.html#working-with-database-schema-">Working with Database Schema</a>.</p>
<p>Rather than using physical types, when creating a table or column you should use <em>abstract types</em>
so that your migrations are independent of specific DBMS. The <a href="./yii-db-schema.html">yii\db\Schema</a> class defines
a set of constants to represent the supported abstract types. These constants are named in the format
of <code>TYPE_&lt;Name&gt;</code>. For example, <code>TYPE_PK</code> refers to auto-incremental primary key type; <code>TYPE_STRING</code>
refers to a string type. When a migration is applied to a particular database, the abstract types
will be translated into the corresponding physical types. In the case of MySQL, <code>TYPE_PK</code> will be turned
into <code>int(11) NOT NULL AUTO_INCREMENT PRIMARY KEY</code>, while <code>TYPE_STRING</code> becomes <code>varchar(255)</code>.</p>
<p>You can append additional constraints when using abstract types. In the above example, <code> NOT NULL</code> is appended
to <code>Schema::TYPE_STRING</code> to specify that the column cannot be null.</p>
<blockquote class="info"><p><strong>Info: </strong>The mapping between abstract types and physical types is specified by
  the <a href="./yii-db-querybuilder.html#$typeMap-detail">$typeMap</a> property in each concrete <code>QueryBuilder</code> class.</p>
</blockquote>
<p>Since version 2.0.6, you can make use of the newly introduced schema builder which provides more convenient way of defining column schema.
So the migration above could be written like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Migration</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150101_185401_create_news_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'news'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string()-&gt;notNull(),
            <span class="hljs-string">'content'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text(),
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'news'</span>);
    }
}
</code></pre>
<p>A list of all available methods for defining the column types is available in the API documentation of <a href="./yii-db-schemabuildertrait.html">yii\db\SchemaBuilderTrait</a>.</p>
<h2>Generating Migrations  <span id="generating-migrations"></span><a href="#generating-migrations" class="hashlink">&para;</a></h2><p>Since version 2.0.7 migration console provides a convenient way to create migrations.</p>
<p>If the migration name is of a special form, for example <code>create_xxx_table</code> or <code>drop_xxx_table</code> then the generated migration
file will contain extra code, in this case for creating/dropping tables.
In the following all variants of this feature are described.</p>
<h3>Create Table <span id="create-table"></span><a href="#create-table" class="hashlink">&para;</a></h3><pre><code class="hljs php language-php">yii migrate/create create_post_table
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">/**
 * Handles the creation for table `post`.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_create_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey()
        ]);
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post'</span>);
    }
}
</code></pre>
<p>To create table fields right away, specify them via <code>--fields</code> option.</p>
<pre><code class="hljs php language-php">yii migrate/create create_post_table --fields=<span class="hljs-string">"title:string,body:text"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">/**
 * Handles the creation for table `post`.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_create_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string(),
            <span class="hljs-string">'body'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text(),
        ]);
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post'</span>);
    }
}

</code></pre>
<p>You can specify more field parameters.</p>
<pre><code class="hljs php language-php">yii migrate/create create_post_table --fields=<span class="hljs-string">"title:string(12):notNull:unique,body:text"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">/**
 * Handles the creation for table `post`.
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_create_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string(<span class="hljs-number">12</span>)-&gt;notNull()-&gt;unique(),
            <span class="hljs-string">'body'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text()
        ]);
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post'</span>);
    }
}
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>primary key is added automatically and is named <code>id</code> by default. If you want to use another name you may
specify it explicitly like <code>--fields="name:primaryKey"</code>.</p>
</blockquote>
<h4>Foreign keys <span id="foreign-keys"></span><a href="#foreign-keys" class="hashlink">&para;</a></h4><p>Since 2.0.8 the generator supports foreign keys using the <code>foreignKey</code> keyword.</p>
<pre><code class="hljs php language-php">yii migrate/create create_post_table --fields=<span class="hljs-string">"author_id:integer:notNull:foreignKey(user),category_id:integer:defaultValue(1):foreignKey,title:string,body:text"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">/**
 * Handles the creation for table `post`.
 * Has foreign keys to the tables:
 *
 * - `user`
 * - `category`
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m160328_040430_create_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'author_id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;integer()-&gt;notNull(),
            <span class="hljs-string">'category_id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;integer()-&gt;defaultValue(<span class="hljs-number">1</span>),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string(),
            <span class="hljs-string">'body'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text(),
        ]);

        <span class="hljs-comment">// creates index for column `author_id`</span>
        <span class="hljs-variable">$this</span>-&gt;createIndex(
            <span class="hljs-string">'idx-post-author_id'</span>,
            <span class="hljs-string">'post'</span>,
            <span class="hljs-string">'author_id'</span>
        );

        <span class="hljs-comment">// add foreign key for table `user`</span>
        <span class="hljs-variable">$this</span>-&gt;addForeignKey(
            <span class="hljs-string">'fk-post-author_id'</span>,
            <span class="hljs-string">'post'</span>,
            <span class="hljs-string">'author_id'</span>,
            <span class="hljs-string">'user'</span>,
            <span class="hljs-string">'id'</span>,
            <span class="hljs-string">'CASCADE'</span>
        );

        <span class="hljs-comment">// creates index for column `category_id`</span>
        <span class="hljs-variable">$this</span>-&gt;createIndex(
            <span class="hljs-string">'idx-post-category_id'</span>,
            <span class="hljs-string">'post'</span>,
            <span class="hljs-string">'category_id'</span>
        );

        <span class="hljs-comment">// add foreign key for table `category`</span>
        <span class="hljs-variable">$this</span>-&gt;addForeignKey(
            <span class="hljs-string">'fk-post-category_id'</span>,
            <span class="hljs-string">'post'</span>,
            <span class="hljs-string">'category_id'</span>,
            <span class="hljs-string">'category'</span>,
            <span class="hljs-string">'id'</span>,
            <span class="hljs-string">'CASCADE'</span>
        );
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// drops foreign key for table `user`</span>
        <span class="hljs-variable">$this</span>-&gt;dropForeignKey(
            <span class="hljs-string">'fk-post-author_id'</span>,
            <span class="hljs-string">'post'</span>
        );

        <span class="hljs-comment">// drops index for column `author_id`</span>
        <span class="hljs-variable">$this</span>-&gt;dropIndex(
            <span class="hljs-string">'idx-post-author_id'</span>,
            <span class="hljs-string">'post'</span>
        );

        <span class="hljs-comment">// drops foreign key for table `category`</span>
        <span class="hljs-variable">$this</span>-&gt;dropForeignKey(
            <span class="hljs-string">'fk-post-category_id'</span>,
            <span class="hljs-string">'post'</span>
        );

        <span class="hljs-comment">// drops index for column `category_id`</span>
        <span class="hljs-variable">$this</span>-&gt;dropIndex(
            <span class="hljs-string">'idx-post-category_id'</span>,
            <span class="hljs-string">'post'</span>
        );

        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post'</span>);
    }
}
</code></pre>
<p>The position of the <code>foreignKey</code> keyword in the column description doesn't
change the generated code. That means:</p>
<ul>
<li><code>author_id:integer:notNull:foreignKey(user)</code></li>
<li><code>author_id:integer:foreignKey(user):notNull</code></li>
<li><code>author_id:foreignKey(user):integer:notNull</code></li>
</ul>
<p>All generate the same code.</p>
<p>The <code>foreignKey</code> keyword can take a parameter between parenthesis which will be
the name of the related table for the generated foreign key. If no parameter
is passed then the table name will be deduced from the column name.</p>
<p>In the example above <code>author_id:integer:notNull:foreignKey(user)</code> will generate a
column named <code>author_id</code> with a foreign key to the <code>user</code> table while
<code>category_id:integer:defaultValue(1):foreignKey</code> will generate a column
<code>category_id</code> with a foreign key to the <code>category</code> table.</p>
<h3>Drop Table <span id="drop-table"></span><a href="#drop-table" class="hashlink">&para;</a></h3><pre><code class="hljs php language-php">yii migrate/create drop_post_table --fields=<span class="hljs-string">"title:string(12):notNull:unique,body:text"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_drop_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string(<span class="hljs-number">12</span>)-&gt;notNull()-&gt;unique(),
            <span class="hljs-string">'body'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text()
        ]);
    }
}
</code></pre>
<h3>Add Column <span id="add-column"></span><a href="#add-column" class="hashlink">&para;</a></h3><p>If the migration name is of the form <code>add_xxx_column_to_yyy_table</code> then the file
content would contain <code>addColumn</code> and <code>dropColumn</code> statements necessary.</p>
<p>To add column:</p>
<pre><code class="hljs php language-php">yii migrate/create add_position_column_to_post_table --fields=<span class="hljs-string">"position:integer"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_add_position_column_to_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;addColumn(<span class="hljs-string">'post'</span>, <span class="hljs-string">'position'</span>, <span class="hljs-variable">$this</span>-&gt;integer());
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropColumn(<span class="hljs-string">'post'</span>, <span class="hljs-string">'position'</span>);
    }
}
</code></pre>
<h3>Drop Column <span id="drop-column"></span><a href="#drop-column" class="hashlink">&para;</a></h3><p>If the migration name is of the form <code>drop_xxx_column_from_yyy_table</code> then
the file content would contain <code>addColumn</code> and <code>dropColumn</code> statements necessary.</p>
<pre><code class="hljs php language-php">yii migrate/create drop_position_column_from_post_table --fields=<span class="hljs-string">"position:integer"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150811_220037_drop_position_column_from_post_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;dropColumn(<span class="hljs-string">'post'</span>, <span class="hljs-string">'position'</span>);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;addColumn(<span class="hljs-string">'post'</span>, <span class="hljs-string">'position'</span>, <span class="hljs-variable">$this</span>-&gt;integer());
    }
}
</code></pre>
<h3>Add Junction Table <span id="add-junction-table"></span><a href="#add-junction-table" class="hashlink">&para;</a></h3><p>If the migration name is of the form <code>create_junction_table_for_xxx_and_yyy_tables</code> or <code>create_junction_xxx_and_yyy_tables</code>
then code necessary to create junction table will be generated.</p>
<pre><code class="hljs php language-php">yii migrate/create create_junction_table_for_post_and_tag_tables --fields=<span class="hljs-string">"created_at:dateTime"</span>
</code></pre>
<p>generates</p>
<pre><code class="hljs php language-php"><span class="hljs-comment">/**
 * Handles the creation for table `post_tag`.
 * Has foreign keys to the tables:
 *
 * - `post`
 * - `tag`
 */</span>
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m160328_041642_create_junction_table_for_post_and_tag_tables</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">up</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'post_tag'</span>, [
            <span class="hljs-string">'post_id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;integer(),
            <span class="hljs-string">'tag_id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;integer(),
            <span class="hljs-string">'created_at'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;dateTime(),
            <span class="hljs-string">'PRIMARY KEY(post_id, tag_id)'</span>,
        ]);

        <span class="hljs-comment">// creates index for column `post_id`</span>
        <span class="hljs-variable">$this</span>-&gt;createIndex(
            <span class="hljs-string">'idx-post_tag-post_id'</span>,
            <span class="hljs-string">'post_tag'</span>,
            <span class="hljs-string">'post_id'</span>
        );

        <span class="hljs-comment">// add foreign key for table `post`</span>
        <span class="hljs-variable">$this</span>-&gt;addForeignKey(
            <span class="hljs-string">'fk-post_tag-post_id'</span>,
            <span class="hljs-string">'post_tag'</span>,
            <span class="hljs-string">'post_id'</span>,
            <span class="hljs-string">'post'</span>,
            <span class="hljs-string">'id'</span>,
            <span class="hljs-string">'CASCADE'</span>
        );

        <span class="hljs-comment">// creates index for column `tag_id`</span>
        <span class="hljs-variable">$this</span>-&gt;createIndex(
            <span class="hljs-string">'idx-post_tag-tag_id'</span>,
            <span class="hljs-string">'post_tag'</span>,
            <span class="hljs-string">'tag_id'</span>
        );

        <span class="hljs-comment">// add foreign key for table `tag`</span>
        <span class="hljs-variable">$this</span>-&gt;addForeignKey(
            <span class="hljs-string">'fk-post_tag-tag_id'</span>,
            <span class="hljs-string">'post_tag'</span>,
            <span class="hljs-string">'tag_id'</span>,
            <span class="hljs-string">'tag'</span>,
            <span class="hljs-string">'id'</span>,
            <span class="hljs-string">'CASCADE'</span>
        );
    }

    <span class="hljs-comment">/**
     * <span class="hljs-doctag">@inheritdoc</span>
     */</span>
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">down</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-comment">// drops foreign key for table `post`</span>
        <span class="hljs-variable">$this</span>-&gt;dropForeignKey(
            <span class="hljs-string">'fk-post_tag-post_id'</span>,
            <span class="hljs-string">'post_tag'</span>
        );

        <span class="hljs-comment">// drops index for column `post_id`</span>
        <span class="hljs-variable">$this</span>-&gt;dropIndex(
            <span class="hljs-string">'idx-post_tag-post_id'</span>,
            <span class="hljs-string">'post_tag'</span>
        );

        <span class="hljs-comment">// drops foreign key for table `tag`</span>
        <span class="hljs-variable">$this</span>-&gt;dropForeignKey(
            <span class="hljs-string">'fk-post_tag-tag_id'</span>,
            <span class="hljs-string">'post_tag'</span>
        );

        <span class="hljs-comment">// drops index for column `tag_id`</span>
        <span class="hljs-variable">$this</span>-&gt;dropIndex(
            <span class="hljs-string">'idx-post_tag-tag_id'</span>,
            <span class="hljs-string">'post_tag'</span>
        );

        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'post_tag'</span>);
    }
}
</code></pre>
<h3>Transactional Migrations  <span id="transactional-migrations"></span><a href="#transactional-migrations" class="hashlink">&para;</a></h3><p>While performing complex DB migrations, it is important to ensure each migration to either succeed or fail as a whole
so that the database can maintain integrity and consistency. To achieve this goal, it is recommended that you
enclose the DB operations of each migration in a <a href="guide-db-dao.html#performing-transactions">transaction</a>.</p>
<p>An even easier way of implementing transactional migrations is to put migration code in the <code>safeUp()</code> and <code>safeDown()</code>
methods. These two methods differ from <code>up()</code> and <code>down()</code> in that they are enclosed implicitly in a transaction.
As a result, if any operation in these methods fails, all prior operations will be rolled back automatically.</p>
<p>In the following example, besides creating the <code>news</code> table we also insert an initial row into this table.</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Migration</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150101_185401_create_news_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">safeUp</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;createTable(<span class="hljs-string">'news'</span>, [
            <span class="hljs-string">'id'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;primaryKey(),
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;string()-&gt;notNull(),
            <span class="hljs-string">'content'</span> =&gt; <span class="hljs-variable">$this</span>-&gt;text(),
        ]);

        <span class="hljs-variable">$this</span>-&gt;insert(<span class="hljs-string">'news'</span>, [
            <span class="hljs-string">'title'</span> =&gt; <span class="hljs-string">'test 1'</span>,
            <span class="hljs-string">'content'</span> =&gt; <span class="hljs-string">'content 1'</span>,
        ]);
    }

    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">safeDown</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;delete(<span class="hljs-string">'news'</span>, [<span class="hljs-string">'id'</span> =&gt; <span class="hljs-number">1</span>]);
        <span class="hljs-variable">$this</span>-&gt;dropTable(<span class="hljs-string">'news'</span>);
    }
}
</code></pre>
<p>Note that usually when you perform multiple DB operations in <code>safeUp()</code>, you should reverse their execution order
in <code>safeDown()</code>. In the above example we first create the table and then insert a row in <code>safeUp()</code>; while
in <code>safeDown()</code> we first delete the row and then drop the table.</p>
<blockquote class="note"><p><strong>Note: </strong>Not all DBMS support transactions. And some DB queries cannot be put into a transaction. For some examples,
  please refer to <a href="http://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html">implicit commit</a>. If this is the case,
  you should still implement <code>up()</code> and <code>down()</code>, instead.</p>
</blockquote>
<h3>Database Accessing Methods  <span id="db-accessing-methods"></span><a href="#db-accessing-methods" class="hashlink">&para;</a></h3><p>The base migration class <a href="./yii-db-migration.html">yii\db\Migration</a> provides a set of methods to let you access and manipulate databases.
You may find these methods are named similarly as the <a href="guide-db-dao.html">DAO methods</a> provided by the <a href="./yii-db-command.html">yii\db\Command</a> class.
For example, the <a href="./yii-db-migration.html#createTable()-detail">yii\db\Migration::createTable()</a> method allows you to create a new table,
just like <a href="./yii-db-command.html#createTable()-detail">yii\db\Command::createTable()</a> does.</p>
<p>The benefit of using the methods provided by <a href="./yii-db-migration.html">yii\db\Migration</a> is that you do not need to explicitly
create <a href="./yii-db-command.html">yii\db\Command</a> instances and the execution of each method will automatically display useful messages
telling you what database operations are done and how long they take.</p>
<p>Below is the list of all these database accessing methods:</p>
<ul>
<li><a href="./yii-db-migration.html#execute()-detail">execute()</a>: executing a SQL statement</li>
<li><a href="./yii-db-migration.html#insert()-detail">insert()</a>: inserting a single row</li>
<li><a href="./yii-db-migration.html#batchInsert()-detail">batchInsert()</a>: inserting multiple rows</li>
<li><a href="./yii-db-migration.html#update()-detail">update()</a>: updating rows</li>
<li><a href="./yii-db-migration.html#delete()-detail">delete()</a>: deleting rows</li>
<li><a href="./yii-db-migration.html#createTable()-detail">createTable()</a>: creating a table</li>
<li><a href="./yii-db-migration.html#renameTable()-detail">renameTable()</a>: renaming a table</li>
<li><a href="./yii-db-migration.html#dropTable()-detail">dropTable()</a>: removing a table</li>
<li><a href="./yii-db-migration.html#truncateTable()-detail">truncateTable()</a>: removing all rows in a table</li>
<li><a href="./yii-db-migration.html#addColumn()-detail">addColumn()</a>: adding a column</li>
<li><a href="./yii-db-migration.html#renameColumn()-detail">renameColumn()</a>: renaming a column</li>
<li><a href="./yii-db-migration.html#dropColumn()-detail">dropColumn()</a>: removing a column</li>
<li><a href="./yii-db-migration.html#alterColumn()-detail">alterColumn()</a>: altering a column</li>
<li><a href="./yii-db-migration.html#addPrimaryKey()-detail">addPrimaryKey()</a>: adding a primary key</li>
<li><a href="./yii-db-migration.html#dropPrimaryKey()-detail">dropPrimaryKey()</a>: removing a primary key</li>
<li><a href="./yii-db-migration.html#addForeignKey()-detail">addForeignKey()</a>: adding a foreign key</li>
<li><a href="./yii-db-migration.html#dropForeignKey()-detail">dropForeignKey()</a>: removing a foreign key</li>
<li><a href="./yii-db-migration.html#createIndex()-detail">createIndex()</a>: creating an index</li>
<li><a href="./yii-db-migration.html#dropIndex()-detail">dropIndex()</a>: removing an index</li>
<li><a href="./yii-db-migration.html#addCommentOnColumn()-detail">addCommentOnColumn()</a>: adding comment to column</li>
<li><a href="./yii-db-migration.html#dropCommentFromColumn()-detail">dropCommentFromColumn()</a>: dropping comment from column</li>
<li><a href="./yii-db-migration.html#addCommentOnTable()-detail">addCommentOnTable()</a>: adding comment to table</li>
<li><a href="./yii-db-migration.html#dropCommentFromTable()-detail">dropCommentFromTable()</a>: dropping comment from table</li>
</ul>
<blockquote class="info"><p><strong>Info: </strong><a href="./yii-db-migration.html">yii\db\Migration</a> does not provide a database query method. This is because you normally do not need
  to display extra message about retrieving data from a database. It is also because you can use the powerful
  <a href="guide-db-query-builder.html">Query Builder</a> to build and run complex queries.</p>
</blockquote>
<blockquote class="note"><p><strong>Note: </strong>When manipulating data using a migration you may find that using your <a href="guide-db-active-record.html">Active Record</a> classes
for this might be useful because some of the logic is already implemented there. Keep in mind however, that in contrast
to code written in the migrations, who's nature is to stay constant forever, application logic is subject to change.
So when using Active Record in migration code, changes to the logic in the Active Record layer may accidentally break
existing migrations. For this reason migration code should be kept independent from other application logic such
as Active Record classes.</p>
</blockquote>
<h2>Applying Migrations  <span id="applying-migrations"></span><a href="#applying-migrations" class="hashlink">&para;</a></h2><p>To upgrade a database to its latest structure, you should apply all available new migrations using the following command:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate
</code></pre>
<p>This command will list all migrations that have not been applied so far. If you confirm that you want to apply
these migrations, it will run the <code>up()</code> or <code>safeUp()</code> method in every new migration class, one after another,
in the order of their timestamp values. If any of the migrations fails, the command will quit without applying
the rest of the migrations.</p>
<blockquote class="tip"><p><strong>Tip: </strong>In case you don't have command line at your server you may try <a href="https://github.com/samdark/yii2-webshell">web shell</a>
extension.</p>
</blockquote>
<p>For each migration that has been successfully applied, the command will insert a row into a database table named
<code>migration</code> to record the successful application of the migration. This will allow the migration tool to identify
which migrations have been applied and which have not.</p>
<blockquote class="info"><p><strong>Info: </strong>The migration tool will automatically create the <code>migration</code> table in the database specified by
  the <a href="./yii-console-controllers-migratecontroller.html#$db-detail">db</a> option of the command. By default, the database
  is specified by the <code>db</code> <a href="guide-structure-application-components.html">application component</a>.</p>
</blockquote>
<p>Sometimes, you may only want to apply one or a few new migrations, instead of all available migrations.
You can do so by specifying the number of migrations that you want to apply when running the command.
For example, the following command will try to apply the next three available migrations:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate <span class="hljs-number">3</span>
</code></pre>
<p>You can also explicitly specify a particular migration to which the database should be migrated
by using the <code>migrate/to</code> command in one of the following formats:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate/to 150101_185401                      <span class="hljs-comment"># using timestamp to specify the migration</span>
yii migrate/to <span class="hljs-string">"2015-01-01 18:54:01"</span>              <span class="hljs-comment"># using a string that can be parsed by strtotime()</span>
yii migrate/to m150101_185401_create_news_table   <span class="hljs-comment"># using full name</span>
yii migrate/to <span class="hljs-number">1392853618</span>                         <span class="hljs-comment"># using UNIX timestamp</span>
</code></pre>
<p>If there are any unapplied migrations earlier than the specified one, they will all be applied before the specified
migration is applied.</p>
<p>If the specified migration has already been applied before, any later applied migrations will be reverted.</p>
<h2>Reverting Migrations  <span id="reverting-migrations"></span><a href="#reverting-migrations" class="hashlink">&para;</a></h2><p>To revert (undo) one or multiple migrations that have been applied before, you can run the following command:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate/down     <span class="hljs-comment"># revert the most recently applied migration</span>
yii migrate/down <span class="hljs-number">3</span>   <span class="hljs-comment"># revert the most 3 recently applied migrations</span>
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>Not all migrations are reversible. Trying to revert such migrations will cause an error and stop the
  entire reverting process.</p>
</blockquote>
<h2>Redoing Migrations  <span id="redoing-migrations"></span><a href="#redoing-migrations" class="hashlink">&para;</a></h2><p>Redoing migrations means first reverting the specified migrations and then applying again. This can be done
as follows:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate/redo        <span class="hljs-comment"># redo the last applied migration</span>
yii migrate/redo <span class="hljs-number">3</span>      <span class="hljs-comment"># redo the last 3 applied migrations</span>
</code></pre>
<blockquote class="note"><p><strong>Note: </strong>If a migration is not reversible, you will not be able to redo it.</p>
</blockquote>
<h2>Listing Migrations  <span id="listing-migrations"></span><a href="#listing-migrations" class="hashlink">&para;</a></h2><p>To list which migrations have been applied and which are not, you may use the following commands:</p>
<pre><code class="hljs bash">yii migrate/<span class="hljs-built_in">history</span>     <span class="hljs-comment"># showing the last 10 applied migrations</span>
yii migrate/<span class="hljs-built_in">history</span> <span class="hljs-number">5</span>   <span class="hljs-comment"># showing the last 5 applied migrations</span>
yii migrate/<span class="hljs-built_in">history</span> all <span class="hljs-comment"># showing all applied migrations</span>

yii migrate/new         <span class="hljs-comment"># showing the first 10 new migrations</span>
yii migrate/new <span class="hljs-number">5</span>       <span class="hljs-comment"># showing the first 5 new migrations</span>
yii migrate/new all     <span class="hljs-comment"># showing all new migrations</span>
</code></pre>
<h2>Modifying Migration History  <span id="modifying-migration-history"></span><a href="#modifying-migration-history" class="hashlink">&para;</a></h2><p>Instead of actually applying or reverting migrations, sometimes you may simply want to mark that your database
has been upgraded to a particular migration. This often happens when you manually change the database to a particular
state and you do not want the migration(s) for that change to be re-applied later. You can achieve this goal with
the following command:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate/mark 150101_185401                      <span class="hljs-comment"># using timestamp to specify the migration</span>
yii migrate/mark <span class="hljs-string">"2015-01-01 18:54:01"</span>              <span class="hljs-comment"># using a string that can be parsed by strtotime()</span>
yii migrate/mark m150101_185401_create_news_table   <span class="hljs-comment"># using full name</span>
yii migrate/mark <span class="hljs-number">1392853618</span>                         <span class="hljs-comment"># using UNIX timestamp</span>
</code></pre>
<p>The command will modify the <code>migration</code> table by adding or deleting certain rows to indicate that the database
has been applied migrations to the specified one. No migrations will be applied or reverted by this command.</p>
<h2>Customizing Migrations  <span id="customizing-migrations"></span><a href="#customizing-migrations" class="hashlink">&para;</a></h2><p>There are several ways to customize the migration command.</p>
<h3>Using Command Line Options  <span id="using-command-line-options"></span><a href="#using-command-line-options" class="hashlink">&para;</a></h3><p>The migration command comes with a few command-line options that can be used to customize its behaviors:</p>
<ul>
<li><p><code>interactive</code>: boolean (defaults to true), specifies whether to perform migrations in an interactive mode.
When this is true, the user will be prompted before the command performs certain actions.
You may want to set this to false if the command is being used in a background process.</p>
</li>
<li><p><code>migrationPath</code>: string (defaults to <code>@app/migrations</code>), specifies the directory storing all migration
class files. This can be specified as either a directory path or a path <a href="guide-concept-aliases.html">alias</a>.
Note that the directory must exist, or the command may trigger an error.</p>
</li>
<li><p><code>migrationTable</code>: string (defaults to <code>migration</code>), specifies the name of the database table for storing
migration history information. The table will be automatically created by the command if it does not exist.
You may also manually create it using the structure <code>version varchar(255) primary key, apply_time integer</code>.</p>
</li>
<li><p><code>db</code>: string (defaults to <code>db</code>), specifies the ID of the database <a href="guide-structure-application-components.html">application component</a>.
It represents the database that will be migrated using this command.</p>
</li>
<li><p><code>templateFile</code>: string (defaults to <code>@yii/views/migration.php</code>), specifies the path of the template file
that is used for generating skeleton migration class files. This can be specified as either a file path
or a path <a href="guide-concept-aliases.html">alias</a>. The template file is a PHP script in which you can use a predefined variable
named <code>$className</code> to get the migration class name.</p>
</li>
<li><p><code>generatorTemplateFiles</code>: array (defaults to `[</p>
<pre><code class="hljs php">  <span class="hljs-string">'create_table'</span> =&gt; <span class="hljs-string">'@yii/views/createTableMigration.php'</span>,
  <span class="hljs-string">'drop_table'</span> =&gt; <span class="hljs-string">'@yii/views/dropTableMigration.php'</span>,
  <span class="hljs-string">'add_column'</span> =&gt; <span class="hljs-string">'@yii/views/addColumnMigration.php'</span>,
  <span class="hljs-string">'drop_column'</span> =&gt; <span class="hljs-string">'@yii/views/dropColumnMigration.php'</span>,
  <span class="hljs-string">'create_junction'</span> =&gt; <span class="hljs-string">'@yii/views/createJunctionMigration.php'</span>
</code></pre>
<p>]`), specifies template files for generating migration code. See "<a href="#generating-migrations">Generating Migrations</a>"
for more details.</p>
</li>
<li><p><code>fields</code>: array of column definition strings used for creating migration code. Defaults to <code>[]</code>. The format of each
definition is <code>COLUMN_NAME:COLUMN_TYPE:COLUMN_DECORATOR</code>. For example, <code>--fields=name:string(12):notNull</code> produces
a string column of size 12 which is not null.</p>
</li>
</ul>
<p>The following example shows how you can use these options.</p>
<p>For example, if we want to migrate a <code>forum</code> module whose migration files
are located within the module's <code>migrations</code> directory, we can use the following
command:</p>
<pre><code class="hljs nginx"><span class="hljs-comment"># migrate the migrations in a forum module non-interactively</span>
<span class="hljs-title">yii</span> migrate --migrationPath=<span class="hljs-variable">@app</span>/modules/forum/migrations --interactive=<span class="hljs-number">0</span>
</code></pre>
<h3>Configuring Command Globally  <span id="configuring-command-globally"></span><a href="#configuring-command-globally" class="hashlink">&para;</a></h3><p>Instead of entering the same option values every time you run the migration command, you may configure it
once for all in the application configuration like shown below:</p>
<pre><code class="hljs php language-php"><span class="hljs-keyword">return</span> [
    <span class="hljs-string">'controllerMap'</span> =&gt; [
        <span class="hljs-string">'migrate'</span> =&gt; [
            <span class="hljs-string">'class'</span> =&gt; <span class="hljs-string">'yii\console\controllers\MigrateController'</span>,
            <span class="hljs-string">'migrationTable'</span> =&gt; <span class="hljs-string">'backend_migration'</span>,
        ],
    ],
];
</code></pre>
<p>With the above configuration, each time you run the migration command, the <code>backend_migration</code> table
will be used to record the migration history. You no longer need to specify it via the <code>migrationTable</code>
command-line option.</p>
<h2>Migrating Multiple Databases  <span id="migrating-multiple-databases"></span><a href="#migrating-multiple-databases" class="hashlink">&para;</a></h2><p>By default, migrations are applied to the same database specified by the <code>db</code> <a href="guide-structure-application-components.html">application component</a>.
If you want them to be applied to a different database, you may specify the <code>db</code> command-line option like shown below,</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate --db=db2
</code></pre>
<p>The above command will apply migrations to the <code>db2</code> database.</p>
<p>Sometimes it may happen that you want to apply <em>some</em> of the migrations to one database, while some others to another
database. To achieve this goal, when implementing a migration class you should explicitly specify the DB component
ID that the migration would use, like the following:</p>
<pre><code class="hljs php language-php"><span class="hljs-preprocessor">&lt;?php</span>

<span class="hljs-keyword">use</span> <span class="hljs-title">yii</span>\<span class="hljs-title">db</span>\<span class="hljs-title">Migration</span>;

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">m150101_185401_create_news_table</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Migration</span>
</span>{
    <span class="hljs-keyword">public</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">init</span><span class="hljs-params">()</span>
    </span>{
        <span class="hljs-variable">$this</span>-&gt;db = <span class="hljs-string">'db2'</span>;
        <span class="hljs-keyword">parent</span>::init();
    }
}
</code></pre>
<p>The above migration will be applied to <code>db2</code>, even if you specify a different database through the <code>db</code> command-line
option. Note that the migration history will still be recorded in the database specified by the <code>db</code> command-line option.</p>
<p>If you have multiple migrations that use the same database, it is recommended that you create a base migration class
with the above <code>init()</code> code. Then each migration class can extend from this base class.</p>
<blockquote class="tip"><p><strong>Tip: </strong>Besides setting the <a href="./yii-db-migration.html#$db-detail">db</a> property, you can also operate on different databases
  by creating new database connections to them in your migration classes. You then use the <a href="guide-db-dao.html">DAO methods</a>
  with these connections to manipulate different databases.</p>
</blockquote>
<p>Another strategy that you can take to migrate multiple databases is to keep migrations for different databases in
different migration paths. Then you can migrate these databases in separate commands like the following:</p>
<pre><code class="hljs nginx"><span class="hljs-title">yii</span> migrate --migrationPath=<span class="hljs-variable">@app</span>/migrations/db1 --db=db1
yii migrate --migrationPath=<span class="hljs-variable">@app</span>/migrations/db2 --db=db2
...
</code></pre>
<p>The first command will apply migrations in <code>@app/migrations/db1</code> to the <code>db1</code> database, the second command
will apply migrations in <code>@app/migrations/db2</code> to <code>db2</code>, and so on.</p>
        <div class="toplink"><a href="#" class="h1" title="go to top"><span class="glyphicon glyphicon-arrow-up"></a></div>
    </div>
</div>


</div>

<footer class="footer">
        <p class="pull-right"><small>Page generated on Sat, 09 Jul 2016 12:16:29 +0000</small></p>
    Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a></footer>

<script type="text/javascript">jQuery(document).ready(function () {
    var shiftWindow = function () { scrollBy(0, -50) };
    if (location.hash) setTimeout(shiftWindow, 1);
    window.addEventListener("hashchange", shiftWindow);
var element = document.createElement("script");
element.src = "./jssearch.index.js";
document.body.appendChild(element);

var searchBox = $('#searchbox');

// search when typing in search field
searchBox.on("keyup", function(event) {
    var query = $(this).val();

    if (query == '' || event.which == 27) {
        $('#search-resultbox').hide();
        return;
    } else if (event.which == 13) {
        var selectedLink = $('#search-resultbox a.selected');
        if (selectedLink.length != 0) {
            document.location = selectedLink.attr('href');
            return;
        }
    } else if (event.which == 38 || event.which == 40) {
        $('#search-resultbox').show();

        var selected = $('#search-resultbox a.selected');
        if (selected.length == 0) {
            $('#search-results').find('a').first().addClass('selected');
        } else {
            var next;
            if (event.which == 40) {
                next = selected.parent().next().find('a').first();
            } else {
                next = selected.parent().prev().find('a').first();
            }
            if (next.length != 0) {
                var resultbox = $('#search-results');
                var position = next.position();

//              TODO scrolling is buggy and jumps around
//                resultbox.scrollTop(Math.floor(position.top));
//                console.log(position.top);

                selected.removeClass('selected');
                next.addClass('selected');
            }
        }

        return;
    }
    $('#search-resultbox').show();
    $('#search-results').html('<li><span class="no-results">No results</span></li>');

    var result = jssearch.search(query);

    if (result.length > 0) {
        var i = 0;
        var resHtml = '';

        for (var key in result) {
            if (i++ > 20) {
                break;
            }
            resHtml = resHtml +
            '<li><a href="' + result[key].file.u.substr(3) +'"><span class="title">' + result[key].file.t + '</span>' +
            '<span class="description">' + result[key].file.d + '</span></a></li>';
        }
        $('#search-results').html(resHtml);
    }
});

// hide the search results on ESC
$(document).on("keyup", function(event) { if (event.which == 27) { $('#search-resultbox').hide(); } });
// hide search results on click to document
$(document).bind('click', function (e) { $('#search-resultbox').hide(); });
// except the following:
searchBox.bind('click', function(e) { e.stopPropagation(); });
$('#search-resultbox').bind('click', function(e) { e.stopPropagation(); });

});</script></body>
</html>
